package com.czb.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czb.seckill.mapper.OrderMapper;
import com.czb.seckill.pojo.Order;
import com.czb.seckill.pojo.SecKillGoods;
import com.czb.seckill.pojo.SecKillOrder;
import com.czb.seckill.pojo.User;
import com.czb.seckill.service.OrderService;
import com.czb.seckill.service.SecKillGoodsService;
import com.czb.seckill.service.SecKillOrderService;
import com.czb.seckill.util.MD5Util;
import com.czb.seckill.util.UUIDUtil;
import com.czb.seckill.vo.GoodsVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: 陈正彬
 */
@Service
public class OrderServiceImpl
        extends ServiceImpl<OrderMapper, Order>
        implements OrderService {

    @Resource
    private SecKillGoodsService secKillGoodsService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SecKillOrderService secKillOrderService;
    @Resource
    private RedisTemplate redisTemplate;

    //完成秒杀
    @Override
    @Transactional
    public Order seckill(User user, GoodsVo goodsVo) {

        //查询秒杀商品的库存，并-1
        SecKillGoods secKillGoods = secKillGoodsService.
                getOne(new QueryWrapper<SecKillGoods>().
                        eq("goods_id", goodsVo.getId()));
        //完成一个基本的秒杀操作，后面在高并发情况下在优化
//        secKillGoods.setStockCount(secKillGoods.getStockCount() -1);
//        secKillGoodsService.updateById(secKillGoods);

        //Mysql在默认的事务隔离级别（REPEATABLE-READ）可重复读 下
        //执行update语句时，会在事务中锁定要更新的行
        //防止其他会话在同一行执行update，delete
        boolean update = secKillGoodsService.update(new UpdateWrapper<SecKillGoods>()
                .setSql("stock_count=stock_count-1")
                .eq("goods_id", goodsVo.getId())
                .gt("stock_count", 0));

        if (!update) {
            //这个条件可以防止更新失败后（库存=0）继续生成订单
            return null;
        }

        //生成普通订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);//设置一个初始值
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(secKillGoods.getSeckillPrice());//秒杀价
        order.setOrderChannel(1);
        order.setStatus(0);//未支付
        order.setCreateDate(new Date());
        //保存order
        orderMapper.insert(order);

        //生成秒杀商品订单
        SecKillOrder secKillOrder = new SecKillOrder();
        secKillOrder.setGoodsId(goodsVo.getId());
        //秒杀商品订单对应的orderId，从普通订单获取
        secKillOrder.setOrderId(order.getId());
        secKillOrder.setUserId(user.getId());
        //保存secKillOrder
        secKillOrderService.save(secKillOrder);

        //将生成的秒杀订单存入到redis,优化查询
        redisTemplate.opsForValue()
                .set("order:" + user.getId() + ":" + goodsVo.getId(), secKillOrder);


        return order;
    }

    //方法生成秒杀路径（唯一）
    @Override
    public String createPath(User user, Long goodsId) {

        //生成秒杀路径
        String path = MD5Util.md5(UUIDUtil.uuid());
        //添加到redis
        redisTemplate.opsForValue().set("seckillPath:" + user.getId() + ":" + goodsId,
                path, 60, TimeUnit.SECONDS);

        return path;
    }

    //方法 对秒杀路径进行校验
    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {

        if (user == null || goodsId < 0 || !StringUtils.hasText(path)) {
            return false;
        }
        //取出该用户秒杀该商品的路径
        String redisPath = (String) redisTemplate.opsForValue().
                get("seckillPath:" + user.getId() + ":" + goodsId);

        return path.equals(redisPath);
    }

    //方法 验证用户的验证码是否正确
    @Override
    public Boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user == null || goodsId < 0 || !StringUtils.hasText(captcha)){
            return false;
        }

        //从redis中取出验证码
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + goodsId);

        return captcha.equals(redisCaptcha);
    }
}
